

package yf.mall.service.impl;
import com.yf.response.RRException;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import yf.mall.common.Const;
import yf.mall.dao.LotteryActDao;
import yf.mall.entity.LotteryActEntity;
import yf.mall.entity.UserEntity;
import yf.mall.enums.AccountTypeEnum;
import yf.mall.enums.MallOrderOrderStatusEnum;
import yf.mall.service.AccountService;
import yf.mall.service.LotteryActService;
import yf.mall.service.UserService;
import yf.mall.vo.LotteryCountNumberVo;
import  yf.mall.vo.down.LotteryCountDown;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.stream.Collectors;
import yf.mall.dao.LotteryCountDao;
import yf.mall.entity.LotteryCountEntity;
import yf.mall.vo.LotteryCountVo;
import yf.mall.service.LotteryCountService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Thu Aug 20 17:10:40 CST 2020
 */
@Service
public class LotteryCountServiceImpl extends BaseServiceImpl<LotteryCountEntity> implements LotteryCountService {

    private LotteryCountDao dao;


    @Autowired
    public void setDao(LotteryCountDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }




    @Override
    public List<LotteryCountVo> findVo(LotteryCountVo vo){
        return dao.findVo(vo);
    }

    @Override
    public LotteryCountVo getVo(Long id){
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(LotteryCountVo vo){
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(LotteryCountVo vo){
        return dao.update(vo.getEntity());
    }



    @Override
    public void downLoad(HttpServletResponse response, List<LotteryCountVo> list) {
        try {
            List<LotteryCountDown> datas = list.stream().map(item -> new LotteryCountDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8" );
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
            EasyExcel.write(response.getOutputStream(), LotteryCountDown.class).sheet("模板" ).doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**内部方法**/



    /**外部方法实现**/


    @Override
    public LotteryCountEntity findByActIdAndUserId(Long actId, Long userId) {
        return dao.findByActIdAndUserId(actId,userId);
    }

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private LotteryActService lotteryActService;

    /**
     * 添加抽奖机会
     * @param userId
     * @param actId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LotteryCountEntity addCount(long userId, Long actId) {
        LotteryActEntity act = this.lotteryActService.get(actId);
        UserEntity userEntity = this.userService.get(userId);
        LotteryCountEntity count = dao.findByActIdAndUserId(actId, userId);
        /**
         * 判断还有没有抽奖机会
         */
        if(act!=null&&act.getCount()!=null&&count!=null&&count.getAmount()>=act.getCount()){
            throw new RRException("请把您的抽奖机会消耗完在添加机会");
        }
        /**
         * 转卷，并增加抽奖机会
         */
        this.accountService.transfer(userId, Const.ADMIN_ID, AccountTypeEnum.COUPON.getIndex(), act.getAmount(), userEntity.getName() + "消耗了" + act.getAmount() + "优惠卷获取了一次机会");
        if (count!=null){
            // 如果已经有抽奖机会加
            count.setAmount(count.getAmount()+1);
            dao.update(count);
        }else {
            //没有抽奖机会自动赋值为1
            count=new LotteryCountEntity(actId,userId,1);
            dao.save(count);
        }
        return count;
    }

    /**
     * 查看抽奖次数
     * @param userId
     * @param status
     * @return
     */
    @Override
    public LotteryCountNumberVo getLotteryCount(Long userId, Integer status) {
        List<LotteryActEntity> lotteryActEntities = lotteryActService.find(null);
 /*       Date startTime = lotteryActEntities.get(0).getStartTime();
        SimpleDateFormat smp = new SimpleDateFormat("yyyy-MM-dd");
        String time = smp.format(startTime);*/
        return dao.getLotteryCount(userId,status);
    }

    /**
     * 手动保存抽奖机会
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLotteryCount(Long userId,LotteryCountNumberVo lotteryCount) {
        // 获取活动
        List<LotteryActEntity> lotteryActEntities = lotteryActService.find(null);
        LotteryCountEntity lotteryCountEntity = new LotteryCountEntity(lotteryActEntities.get(0).getId(),userId,lotteryCount.getCount());
        dao.save(lotteryCountEntity);

    }
}
